package com.bite.system.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.constants.HttpConstants;
import com.bite.common.core.domain.LoginUser;
import com.bite.common.core.domain.R;
import com.bite.common.core.domain.vo.LoginUserVo;
import com.bite.common.core.enums.UserIdentity;
import com.bite.common.security.exception.ServiceException;
import com.bite.common.security.service.TokenService;
import com.bite.system.domain.sysuser.SysUser;
import com.bite.system.domain.sysuser.dto.SysUserSaveDTO;
import com.bite.system.mapper.sysuser.SysUserMapper;
import com.bite.system.service.sysuser.ISysUserService;
import com.bite.system.utils.BCryptUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.bite.common.core.enums.ResultCode.*;

@Service
@Slf4j
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Resource
    private TokenService tokenService;
    @Value("${jwt.secret}")
    private String secret;

    @Override
    public R<String> login(String userAccount, String password) {
        R<Void> loginResult = new R<Void>();
        if(userAccount == null || password == null) {
//             loginResult.setCode(FAILED_PARAMS_VALIDATE.getCode());
//             loginResult.setMsg(FAILED_PARAMS_VALIDATE.getMsg());
            return R.fail(FAILED_PARAMS_VALIDATE);
        }
 
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        //根据用户名查询密码
        SysUser sysUser = sysUserMapper.selectOne(wrapper
                .select(SysUser::getUserId,SysUser::getPassword,SysUser::getNickName).eq(SysUser::getUserAccount, userAccount)
        );
        if(sysUser == null) {
//            loginResult.setCode(FAILED_USER_NOT_EXISTS.getCode());
//            loginResult.setMsg(FAILED_USER_NOT_EXISTS.getMsg());
//            return loginResult;
            log.error("用户名不存在");
            return R.fail(FAILED_USER_NOT_EXISTS);
        }
        if (BCryptUtils.matchesPassword(password,sysUser.getPassword())) {
            log.info("用户正常登录");
            //TODO  赋值给客户端 Token 信息  包含用户的ID和 userKey(Redis中查找信息使用)
            String token = tokenService.createToken(sysUser.getUserId(),
                    secret, UserIdentity.ADMIN.getValue(),sysUser.getNickName(),null);

            return R.ok(token);
        }

        return R.fail(FAILED_LOGIN);

    }

    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
        //在进行管理员新增的时候,判断数据库中是否有此管理员
        List<SysUser> sysUserList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount,sysUserSaveDTO.getUserAccount()));
        if (CollectionUtil.isNotEmpty(sysUserList)) {
            //如果不为空，说明数据库中有同名的管理员
            throw new ServiceException(AILED_USER_EXISTS);
        }

        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));

        return sysUserMapper.insert(sysUser);
    }

    @Override
    public R<LoginUserVo>  info(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if(loginUser == null) {
            return R.fail();
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setNickName(loginUser.getNickName());
        loginUserVo.getNickName();
        return R.ok(loginUserVo);
    }

    @Override
    public boolean logout(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
      return tokenService.deleteLoginUser(token, secret);
    }
}
